#ifndef UTILITY_H
#define UTILITY_H

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <glut.h>
#include <glui.h>
#include "DynamicSimulator.h"

static GLint    ImageWidth=600;
static GLint    ImageHeight=600;


float obj_rot[16];

GLfloat light_position[4]={0.0, 0.0, 3.0, 1.0};

GLfloat eye_position[4]={0,0,-9,1};

GLUI *glui;

DynamicSimulator* ds;


void InitGL();
void DrawElement();
void InitElement();

void InitGL()
{
	glLightfv(GL_LIGHT0, GL_POSITION, light_position);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glDepthFunc(GL_LESS);
	glEnable(GL_DEPTH_TEST);
	//glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);

	glViewport(0, 0, (GLsizei) ImageWidth, (GLsizei) ImageHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f,(GLfloat) ImageWidth / (GLfloat)ImageHeight , 0.5f, -1000.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void DrawElement()
{
	vec3f l, r, n;

	glBegin(GL_TRIANGLES);

	for (int i=0;i<ds->simplex->tetNum;i++)
	{
		Tet *t;
		t = ds->simplex->tets.at(i);

		Vertex *va, *vb, *vc, *vd;
		va = t->vertices[0];
		vb = t->vertices[1];
		vc = t->vertices[2];
		vd = t->vertices[3];

		// a-b-c
		l = vb->position - va->position;
		r = vc->position - va->position;
		n = r ^ l;
		n.Normalize();

		glNormal3f(n[0],n[1],n[2]);

		glVertex3f(va->position[0],va->position[1],va->position[2]);
		glVertex3f(vb->position[0],vb->position[1],vb->position[2]);
		glVertex3f(vc->position[0],vc->position[1],vc->position[2]);

		// a-c-d
		l = vc->position - va->position;
		r = vd->position - va->position;
		n = r ^ l;
		n.Normalize();

		glNormal3f(n[0],n[1],n[2]);

		glVertex3f(va->position[0],va->position[1],va->position[2]);
		glVertex3f(vc->position[0],vc->position[1],vc->position[2]);
		glVertex3f(vd->position[0],vd->position[1],vd->position[2]);

		// a-d-b
		l = vd->position - va->position;
		r = vb->position - va->position;
		n = r ^ l;
		n.Normalize();

		glNormal3f(n[0],n[1],n[2]);

		glVertex3f(va->position[0],va->position[1],va->position[2]);
		glVertex3f(vd->position[0],vd->position[1],vd->position[2]);
		glVertex3f(vb->position[0],vb->position[1],vb->position[2]);

		// b-d-c
		l = vd->position - vb->position;
		r = vc->position - vb->position;
		n = r ^ l;
		n.Normalize();

		glNormal3f(n[0],n[1],n[2]);

		glVertex3f(vb->position[0],vb->position[1],vb->position[2]);
		glVertex3f(vd->position[0],vd->position[1],vd->position[2]);
		glVertex3f(vc->position[0],vc->position[1],vc->position[2]);
		
	}

	glEnd();

}

void InitElement()
{
	ds = new DynamicSimulator();

	ds->LoadVolumetricMesh("dino.abq");

	ds->InitElement();
}

#endif